/*
 * Copyright 2011-2012 OpenAjax Alliance
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

Components.utils.import("resource://oaa-cache-inspector/cache-inspector-common.js");
Components.utils.import("resource://gre/modules/FileUtils.jsm");
Components.utils.import("resource://gre/modules/NetUtil.jsm");


/**
 * @file sidebar-rule-summary.js
 *
 * @desc Supports the sidebar showing rule summary information for a list if cache items 
 */

/* ---------------------------------------------------------------- */
/*            OAA_CI and OAA_CI.ElementView Object             */ 
/* ---------------------------------------------------------------- */

if (typeof OAA_CI === "undefined") {
  var OAA_CI = {};
}

if (typeof OAA_CI.ElementView === "undefined") {
  OAA_CI.ElementView = {};
}


/* ---------------------------------------------------------------- */
/*       Rule Category Cache Item Views and View Controllers        */ 
/* ---------------------------------------------------------------- */

/**
 * @function OAA_CI.ElementView.init
 *
 * @desc Initializes the view
 */
 
OAA_CI.ElementView.init = function () {

  var doc = window.document;
  
  this.nls_strings = doc.getElementById('ID_STRINGBUNDLE_LIST');
  
  this.vbox_element_view  = doc.getElementById('ID_VBOX_ELEMENT_VIEW');
  this.label_element_view = doc.getElementById('ID_LABEL_ELEMENT_VIEW_NAME');
  
  this.hbox_cache_items_expand     = doc.getElementById('ID_HBOX_ELEMENT_VIEW_EXPAND');
  this.tree_cache_items            = doc.getElementById('ID_TREE_ELEMENT_VIEW_ITEMS');
  this.treechildren_cache_items    = doc.getElementById('ID_TREECHILDREN_ELEMENT_VIEW_ITEMS');
  this.treecol_cache_items_order   = doc.getElementById('ID_TREECOL_ORDER');
  this.treecol_cache_items_primary = doc.getElementById('ID_TREECOL_ELEMENT');
  
  this.button_cache_item_report = doc.getElementById('ID_BUTTON_ELEMENT_TYPE_ITEM_REPORT');
  this.button_cache_item_info   = doc.getElementById('ID_BUTTON_ELEMENT_TYPE_ITEM_INFORMATION');
  
  this.sidebar_name = "no name";
  
  this.element_type_results = null;
  
  this.filtered_cache_item_results = [];
  this.cache_item = null;
  
};

/**
 * @function OAA_CI.ElementView.hide
 *
 * @desc Hides the rule category sidebar
 */
 
OAA_CI.ElementView.hide = function () {

  this.vbox_element_view.hidden = true;
  
};


/**
 * @function OAA_CI.ElementView.show
 *
 * @desc Shows the rule category sidebar and updates the contents
 */
 
OAA_CI.ElementView.show = function () {

  this.vbox_element_view.hidden = false;
  
};

/**
 * @function OAA_CI.ElementView.clear
 *
 * @desc Clears the cache item view with a "updating" message
 */
 
OAA_CI.ElementView.clear = function () {

  if (!this.treechildren_cache_items) return;
  if (!this.nls_strings) return;
  
  OAA_CI.removeChildNodes(this.treechildren_cache_items);
  OAA_CI.addTreeItemMessage(this.treechildren_cache_items, this.nls_strings.getString('updating'), '');
  
  this.cacheItemButtonClear();
  
  OAA_CI.ElementResultView.clear();

};

/**
 * @function OAA_CI.ElementView.update
 *
 * @desc Shows a tree of cache items
 */
 
OAA_CI.ElementView.update = function (sidebar_name) {

  function getDOMElement(cache_item) {
    if (cache_item.dom_element) return cache_item.dom_element;
    return cache_item;
  }

  function formatCell(count, style) {

   var treecell = document.createElement('treecell');

   treecell.setAttribute('label', count);
   
   if (count) treecell.setAttribute('properties', style);
   else treecell.setAttribute('properties', 'zero');

   return treecell;  
  }
  
  function updateColumnVisibility(id, flag) {
    var column_node = document.getElementById(id);
    if (flag) column_node.setAttribute('hidden','false');
    else column_node.setAttribute('hidden','true');
  }

  function addTreeItem(treechildren, cache_item_result, level) {
  
//     if (cache_item_result.filtered_children && cache_item_result.filtered_children.length) OAA_WEB_ACCESSIBILITY_LOGGING.logger.log.debug("cache item: " + cache_item_result.cache_item + " (" + cache_item_result.filtered_children.length + ")");
//     else OAA_WEB_ACCESSIBILITY_LOGGING.logger.log.debug("cache item: " + cache_item_result.cache_item + " (0)");
     
     var cache_item = cache_item_result.cache_item;
     var cache_id   = cache_item.cache_id;
     
     filtered_cache_item_results.push(cache_item_result);
        
     var treeitem = document.createElement('treeitem');
     var treerow  = document.createElement('treerow');
        
     var treecell  = document.createElement('treecell');
     treecell.setAttribute('value', cache_id);
     treecell.setAttribute('label', (index));
     treerow.appendChild(treecell);
     cache_item.position = index++;

     var de = getDOMElement(cache_item);
     
     var str = cache_item.toString();
     
//     if (str.length > 33) str = str.substring(0,30) + "...";

     treecell  = document.createElement('treecell');
     if (level === 0) treecell.setAttribute('label', str);
     else treecell.setAttribute('label', cache_item.toString('text'));
     if (de.is_landmark) treecell.setAttribute('properties', 'landmark');
     treerow.appendChild(treecell);
        
     treecell = formatCell(cache_item_result.hidden_count, 'hidden');
     treerow.appendChild(treecell);

     treecell = formatCell(cache_item_result.passed_count, 'passed');
     treerow.appendChild(treecell);

     treecell = formatCell(cache_item_result.warnings_count, 'warning');
     treerow.appendChild(treecell);
        
     treecell = formatCell(cache_item_result.manual_checks_count, 'manual_check');
     treerow.appendChild(treecell);

     treecell = formatCell(cache_item_result.violations_count, 'violation');
     treerow.appendChild(treecell);

     treeitem.appendChild(treerow);

     if (cache_item_result.filtered_children) {
       var children_len = cache_item_result.filtered_children.length;
       
       if (children_len) {
       
         var sub_treechildren = document.createElement('treechildren');
     
         for (var i = 0; i < children_len; i++) addTreeItem(sub_treechildren, cache_item_result.filtered_children[i], (level+1));
     
         treeitem.appendChild(sub_treechildren);
         treeitem.setAttribute('container', 'true');        
         treeitem.setAttribute('open',      'true');        
       }    
     }
     treechildren.appendChild(treeitem);
 
  }

  var treechildren_cache_items = this.treechildren_cache_items;
  var nls_strings  = this.nls_strings;

  if (!treechildren_cache_items || !nls_strings) return;
  
  this.sidebar_name = sidebar_name;
  
  var prefs = OAA_WEB_ACCESSIBILITY_PREF.util.getPreferences();
  
  this.clear();
  OAA_CI.removeChildNodes(this.treechildren_cache_items);
    
  this.label_element_view.setAttribute('value', this.sidebar_name);
  
  if (!OAA_CI.ruleset) OAA_CI.updateEvaluation();
  
  var mainWindow = window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
  .getInterface(Components.interfaces.nsIWebNavigation)
  .QueryInterface(Components.interfaces.nsIDocShellTreeItem)
  .rootTreeItem
  .QueryInterface(Components.interfaces.nsIInterfaceRequestor)
  .getInterface(Components.interfaces.nsIDOMWindow);
  
  var sidebar_option = mainWindow.oaa_sidebar_option;
  var sidebar_name   = mainWindow.oaa_sidebar_name;

  OAA_WEB_ACCESSIBILITY_LOGGING.logger.log.debug("Sidebar Name: " + sidebar_name + "  Option: " + sidebar_option);

  this.element_type_results = OAA_CI.ruleset.getCacheItemsByElementType(sidebar_option, prefs.show_results_filter_value); 
  
  var cache_item_results = this.element_type_results.cache_item_results;
  var cache_item_results_len = cache_item_results.length;

  OAA_WEB_ACCESSIBILITY_LOGGING.logger.log.debug("IS A TREE: " + this.element_type_results.is_tree + " Item Count:" + cache_item_results.length);

  if (this.element_type_results && this.element_type_results.is_tree) {
    this.treecol_cache_items_order.hidden = true;
    this.treecol_cache_items_primary.setAttribute('primary', 'true');
    this.hbox_cache_items_expand.hidden = false;
  }
  else {
    this.treecol_cache_items_order.hidden = false;
    this.treecol_cache_items_primary.setAttribute('primary', 'false');
    this.hbox_cache_items_expand.hidden = true;
  }

  this.filtered_cache_item_results     = [];  
  var filtered_cache_item_results = this.filtered_cache_item_results;
    
  var index = 1;

//  OAA_WEB_ACCESSIBILITY_LOGGING.logger.log.debug("CACHE ITEM RESULTS: " + cache_item_results + " (" + cache_item_results_len + ")");
//  OAA_WEB_ACCESSIBILITY_LOGGING.logger.log.debug("FILTERED RESULTS: " + this.element_type_results.number_of_cache_items_filtered);

  var cache_item_result;
  var props;

  if (cache_item_results_len === 0 && this.element_type_results.number_of_cache_items_filtered <= 0) {
    OAA_CI.addTreeItemMessage(treechildren_cache_items, this.nls_strings.getString('noCacheItems'), '');
  }
  else {
  
    for (var i = 0; i < cache_item_results_len; i++) addTreeItem(treechildren_cache_items, cache_item_results[i], 0);

//    OAA_WEB_ACCESSIBILITY_LOGGING.logger.log.debug("FILTERED RESULTS: " + this.element_type_results.number_of_cache_items_filtered);
      
    if (this.element_type_results.number_of_cache_items_filtered > 0) {
      var str;
      if (this.element_type_results.number_of_cache_items_filtered < 2) str = this.element_type_results.number_of_cache_items_filtered + " " + this.nls_strings.getString('filteredItem');
      else str = this.element_type_results.number_of_cache_items_filtered + " "  + this.nls_strings.getString('filteredItems');
      
      OAA_CI.addTreeItemMessage(treechildren_cache_items, str, 'filtered');
    }

  }
      
  // Update the columns displayed
  
  updateColumnVisibility('ID_TREECOL_PASSED',        prefs.show_results_pass);
  updateColumnVisibility('ID_TREECOL_MANUAL_CHECKS', (prefs.show_results_page_manual_checks | prefs.show_results_element_manual_checks));
  updateColumnVisibility('ID_TREECOL_WARNINGS',      prefs.show_results_warnings);
  updateColumnVisibility('ID_TREECOL_HIDDEN',        prefs.show_results_hidden);

};

/**
 * @function OAA_CI.ElementView.onSelect
 *
 * @desc Updates node results when a cache item is selected
 */
 
OAA_CI.ElementView.onSelect = function () {

  var tree = OAA_CI.ElementView.tree_cache_items;

  if (tree) {
  
    var index = tree.currentIndex;
 
    var cache_id = OAA_CI.getCacheIdFromTree(tree, index);
 
    if (!cache_id) return;
 
    var cache_item_results      = this.filtered_cache_item_results;
    var cache_item_results_len  = cache_item_results.length;
    var cache_item_result      = null;
    var cache_item             = null;
    var cache_item_position    = -1;

//    OAA_WEB_ACCESSIBILITY_LOGGING.logger.log.debug("Index: " + index + " CACHE ID: " + cache_id + " # number of cache items: " + cache_item_results_len);  

    if (cache_id === 'filtered') {
      OAA_CI.ElementView.cacheItemButtonClear();
      OAA_CI.ElementResultView.clear();  
    }
    else {

      for (var i = 0; i < cache_item_results_len; i++ ) {
        var ci_result = cache_item_results[i];
        if (cache_id == ci_result.cache_item.cache_id) {
          cache_item_result = ci_result;
          cache_item        = ci_result.cache_item;
          cache_item_position = i + 1;
          break;    
        }    
      } // end loop
      OAA_CI.ElementResultView.update(cache_item_result);  
    
      OAA_CI.ElementView.cacheItemButtonUpdate(cache_item_position, cache_item);  

//      if (cache_item) OAA_WEB_ACCESSIBILITY_LOGGING.logger.log.debug("CACHE ITEM HIGHLIGHT: " + cache_item + "  dom Element: " + cache_item.dom_element  + "  node: " + cache_item.dom_element.node);
//      else OAA_WEB_ACCESSIBILITY_LOGGING.logger.log.debug("CACHE ITEM HIGHLIGHT: is null");
    
      OAA_CI.highlightCacheItems(OAA_CI.ruleset.doc, cache_item);
    
    }  
  } 
};


/**
 * @function OAA_CI.ElementView.showCacheItemReport
 *
 * @desc Opens a new tab in the window to display an HTML view of the report
 */
 
OAA_CI.ElementView.showCacheItemReport = function () {

  if (!this.element_type_results) return;

  var dir = FileUtils.getDir('TmpD', [], true, true);

  var file = FileUtils.getFile('TmpD', ['report_element_type.html']);
  
  var fileStream = FileUtils.openSafeFileOutputStream(file, 0x02 | 0x08 | 0x20, 0644, 0);  
  
  var html = this.element_type_results.toHTML(this.sidebar_name);
  
  fileStream.write(html, html.length);
  
  FileUtils.closeSafeFileOutputStream(fileStream);
    
  OAA_WEB_ACCESSIBILITY_LOGGING.logger.log.debug("Report Element Type URL: " + file.path);
  
  var mainWindow = window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
   .getInterface(Components.interfaces.nsIWebNavigation)
   .QueryInterface(Components.interfaces.nsIDocShellTreeItem)
   .rootTreeItem
   .QueryInterface(Components.interfaces.nsIInterfaceRequestor)
   .getInterface(Components.interfaces.nsIDOMWindow);

  mainWindow.gBrowser.addTab(file.path);

  file = FileUtils.getFile('TmpD', ['report_element_type.csv']);
  
  fileStream = FileUtils.openSafeFileOutputStream(file, 0x02 | 0x08 | 0x20, 0644, 0);  
  
  var csv = this.element_type_results.toCSV(this.sidebar_name);
  
  fileStream.write(csv, csv.length);
  
  FileUtils.closeSafeFileOutputStream(fileStream);

};

/**
 * @function OAA_CI.ElementView.showCacheItemInformation
 *
 * @desc Show information about the currently selected element 
 */
 
OAA_CI.ElementView.showCacheItemInformation = function () {

//  OAA_WEB_ACCESSIBILITY_LOGGING.logger.log.debug("Cache Item Information: " + OAA_CI.ElementView.cache_item);

  if (OAA_CI.ElementView.cache_item) {
    if (!OAA_CI.cache_item_properties_dialog || 
        !OAA_CI.cache_item_properties_dialog.cache_item_properties) {
      OAA_CI.showCacheItemPropertiesDialog(OAA_CI.ElementView.cache_item);
    } 
  }   
  else {
    OAA_CI_UTILS.preferencesDialog();
  }  

};

/* ---------------------------------------------------------------- */
/*                    Cache Item Information Button                 */ 
/* ---------------------------------------------------------------- */

/**
 * @function OAA_CI.ElementView.cacheItemButtonClear
 *
 * @desc Clears the rules in the rules tabs
 */
 
OAA_CI.ElementView.cacheItemButtonClear = function () {


  if (this.nls_strings && this.button_cache_item_info) {
    var label   = this.nls_strings.getString('element') + " " + this.nls_strings.getString('information');
    
    this.button_cache_item_info.setAttribute("label", label);
    this.button_cache_item_info.setAttribute('tooltiptext', this.nls_strings.getString('noElementSelected'));
    this.button_cache_item_info.setAttribute("disabled",    "true");
  }
  
  if (OAA_CI.cache_item_properties_dialog && 
      OAA_CI.cache_item_properties_dialog.cache_item_properties) {
    OAA_CI.cache_item_properties_dialog.cache_item_properties.clear();
  }

  this.cache_item = null;
  
};

/**
 * @function OAA_CI.ElementView.cacheItemButtonUpdate
 *
 * @desc Updates the lable of the show cache item information button
 *
 * @param {Number}     position    - Position of cache item object in a list    
 * @param {CacheItem}  cache_item  - cache item object    
 */
 
OAA_CI.ElementView.cacheItemButtonUpdate = function (position, cache_item) {

  if (!this.nls_strings || !this.button_cache_item_info) return;

  if (cache_item) {
  
    var label   = this.nls_strings.getString('element') + " " + position + " " + this.nls_strings.getString('information');
    var tooltip = this.nls_strings.getString('moreInformationRule') + ": " + cache_item.toString();
    
    this.button_cache_item_info.setAttribute("label", label);
    this.button_cache_item_info.setAttribute("tooltiptext",  tooltip);
    this.button_cache_item_info.setAttribute("disabled", "false");

    if (OAA_CI.cache_item_properties_dialog && 
        OAA_CI.cache_item_properties_dialog.cache_item_properties) {
      OAA_CI.cache_item_properties_dialog.cache_item_properties.update(cache_item);
    }
    
    this.cache_item = cache_item;

  }  
  else {
    this.cacheItemButtonClear();
    
    if (OAA_CI.cache_item_properties_dialog && 
        OAA_CI.cache_item_properties_dialog.cache_item_properties) {
      OAA_CI.cache_item_properties_dialog.cache_item_properties.clear();
    }
  }
};



